package com.devilvan.customPartition;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

public class CustomPartitionMain extends Configured implements Tool {

    @Override
    public int run(String[] args) throws Exception {
        FileSystem fileSystem = FileSystem.get(super.getConf());
        if (fileSystem.exists(new Path(args[1]))) fileSystem.delete(new Path(args[1]),true);
        Job job = Job.getInstance(super.getConf(), "customPartition");
        job.setJarByClass(this.getClass());
        // inputFormat
        job.setInputFormatClass(TextInputFormat.class);
        TextInputFormat.addInputPath(job, new Path(args[0]));
        // mapper
        job.setMapperClass(CustomPartitionMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(FlowEntity.class);
        // partitioner
//        job.setPartitionerClass(CustomPartition.class);
        // reduce
        job.setReducerClass(CustomPartitionReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        // outputFormat
        job.setOutputFormatClass(TextOutputFormat.class);
        TextOutputFormat.setOutputPath(job,new Path(args[1]));
        // reduceTask
        job.setNumReduceTasks(Integer.parseInt(args[2]));
        // completion
        boolean flag = job.waitForCompletion(true);
        return flag ? 0 : 1;
    }

    public static void main(String[] args) throws Exception {
        int run = ToolRunner.run(new Configuration(),new CustomPartitionMain(), args);
        System.exit(run);
    }
}
